# AIQuant 开发环境配置
# 开发友好、调试便利的配置

import os
from typing import List, Optional
from pydantic import BaseSettings, validator
from datetime import timedelta

class DevelopmentSettings(BaseSettings):
    """开发环境配置类"""
    
    # =============================================================================
    # 基础配置
    # =============================================================================
    ENVIRONMENT: str = "development"
    DEBUG: bool = True
    TESTING: bool = False
    
    # 应用信息
    APP_NAME: str = "AIQuant-Dev"
    APP_VERSION: str = "1.0.0-dev"
    APP_DESCRIPTION: str = "AI-powered Quantitative Investment Research System (Development)"
    
    # =============================================================================
    # 服务器配置
    # =============================================================================
    # API服务器
    API_HOST: str = "127.0.0.1"
    API_PORT: int = 8000
    API_WORKERS: int = 1
    API_RELOAD: bool = True
    API_RELOAD_DIRS: List[str] = ["aiquant"]
    API_LOG_LEVEL: str = "debug"
    
    # Web仪表板
    WEB_HOST: str = "127.0.0.1"
    WEB_PORT: int = 8501
    WEB_SERVER_HEADLESS: bool = False
    WEB_SERVER_ENABLE_CORS: bool = True
    WEB_SERVER_ENABLE_XSRF_PROTECTION: bool = False
    WEB_BROWSER_GATHER_USAGE_STATS: bool = False
    
    # =============================================================================
    # 数据库配置
    # =============================================================================
    # PostgreSQL开发库
    DATABASE_URL: str = "postgresql://aiquant:aiquant_dev_password@localhost:5432/aiquant_dev"
    DATABASE_POOL_SIZE: int = 5
    DATABASE_MAX_OVERFLOW: int = 10
    DATABASE_POOL_TIMEOUT: int = 30
    DATABASE_POOL_RECYCLE: int = 3600
    DATABASE_POOL_PRE_PING: bool = True
    DATABASE_ECHO: bool = True  # 开发环境显示SQL
    DATABASE_ECHO_POOL: bool = False
    
    # 数据库连接重试
    DATABASE_RETRY_ATTEMPTS: int = 3
    DATABASE_RETRY_DELAY: int = 2
    
    # 时间序列数据库
    TIMESCALE_CHUNK_TIME_INTERVAL: str = "1 hour"  # 开发环境更小的块
    TIMESCALE_COMPRESSION_ENABLED: bool = False  # 开发环境关闭压缩
    
    # =============================================================================
    # Redis配置
    # =============================================================================
    REDIS_URL: str = "redis://localhost:6379/0"
    REDIS_POOL_SIZE: int = 10
    REDIS_POOL_MAX_CONNECTIONS: int = 20
    REDIS_SOCKET_TIMEOUT: int = 5
    REDIS_SOCKET_CONNECT_TIMEOUT: int = 5
    REDIS_SOCKET_KEEPALIVE: bool = True
    REDIS_HEALTH_CHECK_INTERVAL: int = 30
    
    # =============================================================================
    # Celery配置
    # =============================================================================
    CELERY_BROKER_URL: str = "redis://localhost:6379/1"
    CELERY_RESULT_BACKEND: str = "redis://localhost:6379/2"
    CELERY_TASK_SERIALIZER: str = "json"
    CELERY_RESULT_SERIALIZER: str = "json"
    CELERY_ACCEPT_CONTENT: List[str] = ["json"]
    CELERY_TIMEZONE: str = "Asia/Shanghai"
    CELERY_ENABLE_UTC: bool = True
    
    # Worker配置（开发环境单进程）
    CELERY_WORKER_CONCURRENCY: int = 1
    CELERY_WORKER_PREFETCH_MULTIPLIER: int = 1
    CELERY_WORKER_MAX_TASKS_PER_CHILD: int = 100
    CELERY_WORKER_DISABLE_RATE_LIMITS: bool = True
    CELERY_WORKER_LOG_LEVEL: str = "debug"
    
    # 任务配置
    CELERY_TASK_SOFT_TIME_LIMIT: int = 60
    CELERY_TASK_TIME_LIMIT: int = 120
    CELERY_TASK_ACKS_LATE: bool = False
    CELERY_TASK_REJECT_ON_WORKER_LOST: bool = False
    CELERY_TASK_IGNORE_RESULT: bool = False
    CELERY_TASK_EAGER: bool = False  # 设为True可同步执行任务
    
    # 结果后端配置
    CELERY_RESULT_EXPIRES: int = 1800  # 30分钟
    CELERY_RESULT_PERSISTENT: bool = False
    
    # Beat调度器配置（开发环境更频繁的调度）
    CELERY_BEAT_SCHEDULE: dict = {
        'market-data-sync-dev': {
            'task': 'aiquant.tasks.sync_market_data',
            'schedule': 300.0,  # 每5分钟
        },
        'system-health-check-dev': {
            'task': 'aiquant.tasks.health_check',
            'schedule': 60.0,  # 每分钟
        },
    }
    
    # =============================================================================
    # 安全配置（开发环境宽松）
    # =============================================================================
    SECRET_KEY: str = "dev-secret-key-change-in-production-12345678901234567890"
    JWT_SECRET_KEY: str = "dev-jwt-secret-key-change-in-production-12345678901234567890"
    JWT_ALGORITHM: str = "HS256"
    JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 60  # 开发环境更长过期时间
    JWT_REFRESH_TOKEN_EXPIRE_DAYS: int = 30
    
    # CORS配置（开发环境允许所有来源）
    CORS_ORIGINS: List[str] = ["*"]
    CORS_ALLOW_CREDENTIALS: bool = True
    CORS_ALLOW_METHODS: List[str] = ["*"]
    CORS_ALLOW_HEADERS: List[str] = ["*"]
    
    # 速率限制（开发环境关闭）
    RATE_LIMIT_ENABLED: bool = False
    
    # SSL/TLS配置（开发环境关闭）
    SSL_ENABLED: bool = False
    
    # =============================================================================
    # 日志配置
    # =============================================================================
    LOG_LEVEL: str = "DEBUG"
    LOG_FORMAT: str = "%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s"
    LOG_DATE_FORMAT: str = "%Y-%m-%d %H:%M:%S"
    
    # 日志文件配置
    LOG_FILE_ENABLED: bool = True
    LOG_FILE_PATH: str = "logs/aiquant-dev.log"
    LOG_FILE_MAX_SIZE: int = 10 * 1024 * 1024  # 10MB
    LOG_FILE_BACKUP_COUNT: int = 3
    LOG_FILE_ROTATION: str = "midnight"
    
    # 控制台日志
    LOG_CONSOLE_ENABLED: bool = True
    LOG_CONSOLE_LEVEL: str = "DEBUG"
    LOG_CONSOLE_FORMAT: str = "%(levelname)s - %(name)s - %(message)s"
    
    # 结构化日志（开发环境关闭）
    LOG_JSON_FORMAT: bool = False
    LOG_INCLUDE_TRACE_ID: bool = True
    
    # 外部日志服务（开发环境关闭）
    LOG_ELASTICSEARCH_ENABLED: bool = False
    
    # =============================================================================
    # 监控配置
    # =============================================================================
    # Prometheus指标（开发环境简化）
    METRICS_ENABLED: bool = True
    METRICS_PORT: int = 9090
    METRICS_PATH: str = "/metrics"
    
    # 健康检查
    HEALTH_CHECK_ENABLED: bool = True
    HEALTH_CHECK_PATH: str = "/health"
    HEALTH_CHECK_TIMEOUT: int = 10
    
    # 性能监控
    PERFORMANCE_MONITORING_ENABLED: bool = True
    SLOW_QUERY_THRESHOLD: float = 0.5  # 开发环境更严格
    SLOW_REQUEST_THRESHOLD: float = 1.0
    
    # APM配置（开发环境关闭）
    APM_ENABLED: bool = False
    
    # =============================================================================
    # 缓存配置
    # =============================================================================
    CACHE_ENABLED: bool = True
    CACHE_DEFAULT_TIMEOUT: int = 60  # 开发环境更短的缓存时间
    CACHE_KEY_PREFIX: str = "aiquant:dev:"
    
    # 缓存策略
    CACHE_MARKET_DATA_TIMEOUT: int = 30
    CACHE_USER_SESSION_TIMEOUT: int = 600  # 10分钟
    CACHE_API_RESPONSE_TIMEOUT: int = 60
    
    # =============================================================================
    # 业务配置
    # =============================================================================
    # 市场数据
    MARKET_DATA_PROVIDERS: List[str] = ["akshare"]  # 开发环境使用免费数据源
    MARKET_DATA_UPDATE_INTERVAL: int = 300  # 5分钟
    MARKET_DATA_RETENTION_DAYS: int = 30  # 开发环境保留更少数据
    
    # 交易配置
    TRADING_ENABLED: bool = False
    TRADING_MODE: str = "simulation"
    TRADING_COMMISSION_RATE: float = 0.0003
    TRADING_SLIPPAGE_RATE: float = 0.0001
    
    # 风险管理（开发环境宽松）
    RISK_MONITORING_ENABLED: bool = True
    MAX_POSITION_SIZE: float = 0.2  # 20%
    MAX_DAILY_LOSS: float = 0.1  # 10%
    STOP_LOSS_THRESHOLD: float = 0.05  # 5%
    
    # 智能体配置
    AGENT_MAX_CONCURRENT: int = 3  # 开发环境限制并发
    AGENT_TIMEOUT: int = 60
    AGENT_RETRY_ATTEMPTS: int = 2
    
    # =============================================================================
    # 外部服务配置
    # =============================================================================
    # 邮件服务（开发环境关闭）
    EMAIL_ENABLED: bool = False
    
    # 消息通知（开发环境关闭）
    NOTIFICATION_ENABLED: bool = False
    
    # 第三方API（开发环境使用测试配置）
    OPENAI_API_KEY: Optional[str] = None
    OPENAI_MODEL: str = "gpt-3.5-turbo"  # 开发环境使用更便宜的模型
    OPENAI_MAX_TOKENS: int = 1000
    OPENAI_TEMPERATURE: float = 0.1
    
    # =============================================================================
    # 开发工具配置
    # =============================================================================
    # 热重载
    AUTO_RELOAD: bool = True
    RELOAD_INCLUDES: List[str] = ["*.py", "*.yaml", "*.yml", "*.json"]
    RELOAD_EXCLUDES: List[str] = ["*.pyc", "__pycache__", ".git"]
    
    # 调试工具
    DEBUG_TOOLBAR_ENABLED: bool = True
    PROFILER_ENABLED: bool = True
    MEMORY_PROFILER_ENABLED: bool = True
    
    # 测试数据
    USE_TEST_DATA: bool = True
    TEST_DATA_PATH: str = "data/test"
    MOCK_EXTERNAL_APIS: bool = True
    
    # 开发服务器
    DEV_SERVER_RELOAD: bool = True
    DEV_SERVER_RELOAD_DIRS: List[str] = ["aiquant", "config", "scripts"]
    
    # =============================================================================
    # 性能优化配置
    # =============================================================================
    # 数据库查询优化
    DATABASE_QUERY_CACHE_ENABLED: bool = False  # 开发环境关闭查询缓存
    DATABASE_SLOW_QUERY_LOG: bool = True
    
    # 异步处理
    ASYNC_POOL_SIZE: int = 10
    ASYNC_TIMEOUT: int = 30
    
    # 内存管理
    MEMORY_LIMIT_MB: int = 1024
    MEMORY_WARNING_THRESHOLD: float = 0.9
    
    # =============================================================================
    # 备份和恢复（开发环境简化）
    # =============================================================================
    BACKUP_ENABLED: bool = False
    
    # =============================================================================
    # 验证器（开发环境宽松）
    # =============================================================================
    @validator('SECRET_KEY', 'JWT_SECRET_KEY')
    def validate_secret_keys(cls, v):
        # 开发环境允许默认密钥，但给出警告
        if v.startswith('dev-'):
            print(f"WARNING: Using development secret key. Change in production!")
        return v
    
    @validator('LOG_LEVEL')
    def validate_log_level(cls, v):
        valid_levels = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
        if v.upper() not in valid_levels:
            raise ValueError(f'LOG_LEVEL must be one of {valid_levels}')
        return v.upper()
    
    class Config:
        env_file = ".env.development"
        env_file_encoding = "utf-8"
        case_sensitive = True
        
        # 环境变量前缀
        env_prefix = "AIQUANT_"
        
        # 字段别名
        fields = {
            'DATABASE_URL': {'env': ['DATABASE_URL', 'POSTGRES_URL', 'DEV_DATABASE_URL']},
            'REDIS_URL': {'env': ['REDIS_URL', 'CACHE_URL', 'DEV_REDIS_URL']},
        }

# 创建配置实例
settings = DevelopmentSettings()

# 导出常用配置
__all__ = ['settings', 'DevelopmentSettings']